#include "lrc.h"
#include <QDebug>

using namespace std;


// cannot sort for list
//class Lrc_sort {
//    bool operator()(const lrc& a, const lrc& b) const {
//        return a.time < b.time;
//    }
//};

lrc::lrc()
{

}

lrc::lrc(float time , string name)
{
    this->time = time;
    this->name = name;
}

bool lrc::operator< (lrc &a )
{
    return this->time < a.time;
}


void lrc::load_lrc_file(FILE * fp , list<lrc> * lrc_list, S_LRC_HEAD* lrc_head)
{


    char buf_lrc[128];
    // read str from file

    int line_num = 0;
    while(   fgets(buf_lrc , sizeof(buf_lrc) , fp ) != NULL  )
    {
        line_num++;
        if(line_num <= 4 )
        {
            resolve_lrc_head( buf_lrc , lrc_head);
            continue;
        }

        // put lrc into list
        resolve_single_lrc(lrc_list, buf_lrc);
        lrc_list->sort();




    }


    list<lrc>::iterator it =  lrc_list->begin();
    for(; it != lrc_list->end() ; it++)
    {
        cout << (*it).time <<  " " << (*it).name << endl;
    }

    printf("%s" , buf_lrc);

    cout << lrc_list->size() <<endl;

}


void lrc::resolve_lrc_head(char* buf , S_LRC_HEAD* lrc_head)
{
    if(*buf!='[')
        return ;
    char tmp_str_key[2];
    memset(tmp_str_key , 2 ,1);
    char tmp_str_value[20];
    memset(tmp_str_value , 20 ,1);
    sscanf(buf , "[%2s:%[^]]" , tmp_str_key , tmp_str_value  );

     qDebug() << tmp_str_key << ":" << tmp_str_value;

    if(strncmp("ti" , tmp_str_key , strlen("ti"))== 0 )
    {

        strncpy(lrc_head->ti, tmp_str_value , strlen(tmp_str_value));

    }else if(strncmp("ar" , tmp_str_key , strlen("ar"))== 0)
    {
        strncpy(lrc_head->ar, tmp_str_value , strlen(tmp_str_value));
    }else if(strncmp("al" , tmp_str_key , strlen("al"))== 0)
    {
        strncpy(lrc_head->al, tmp_str_value , strlen(tmp_str_value));

    }else
    {

    }

}




void lrc::resolve_single_lrc(list<lrc> * lrc_list, char *buf)
{
    int min;
    float sec;
    int apperance_times=0;
    float times[20] = {0};

    char *p = buf;
    while( *p == '[' )
    {
        sscanf(p , "[%d:%f" , &min , &sec);
//        cout << min << "---" << sec <<endl;
        times[apperance_times] = 60 * min + sec;
        p = p + 10;
        apperance_times++;
    }



    int j;
    for(j = 0; j < apperance_times; j++)
    {
//        cout << "xxxx" <<endl;
        lrc_list->push_back(lrc(times[j] , p));
    }


}

